/**
 *资源目录树
 */
define([
    "dojo/_base/declare",
    "esri/layers/MapImageLayer",
    "esri/layers/FeatureLayer",
], function (declare,MapImageLayer,FeatureLayer) {

    return declare(null, {
        /**
         * 成员属性
         * @type {string}
         */
        view: Context.view,//地图视图
        urls:{
           getAllRes:"/admin/mapres/mapres/searchAllRes"
        },

        /**
         * 获取素有通用的元素
         * (建议通过function的方式返回，防止因为缓存的原因导致元素事件无法激活)
         * @returns
         */
        elements:function(){//每次加载后均需要重新选择
            return{
            };
        },
        /**
         * 构造函数（初始化函数）
         */
        constructor: function () {
            this.init();
        },
        /**
         * 初始化函数
         */
        init:function () {
            // this.initCatalog();

            this.initUIEvent();
            this.initOpt();

            this.addLayerDefault();
        },
        initCatalog:function () {
            let that=this;
            $.ajax({
                url : that.urls.getAllRes,
                data : {
                },
                type : 'get',
                headers: {
                    'Authorization':CommonUtils.getToken()
                },//通过请求头来发送token
                dataType : 'json',
                async : true,
                success : function(result) {
                    if(CommonUtils.handlerRes(result)){
                        var html='';
                        if(result.code=="200"){
                            var data=result.data;
                            for(var i=0;i<data.length;i++){
                                html+='<li class="mui-table-view-cell">' +
                                    '<span data-url="'+data[i].url+'"' +
                                    ' data-name="'+data[i].title+'" data-id="'+data[i].id+'" data-layerId="'+data[i].layerId+'" data-showFields="'+data[i].showFields+'">'+data[i].title+'</span>' +
                                    '<div class="mui-switch"><div class="mui-switch-handle"></div></div></li>';
                            }
                            $("#J_ResTree").html(html);
                        }
                        that.initMenu();
                    }

                },
                error : function(msg) {
                    alert(CommonUtils.getExceptionMsg());
                }
            });
        },
        initMenu:function () {
            var that=this;
            mui('.mui-content .mui-switch').each(function() { //循环所有toggle
                //toggle.classList.contains('mui-active') 可识别该toggle的开关状态
                // this.parentNode.querySelector('span').innerText = '数据资源：' + (this.classList.contains('mui-active') ? 'true' : 'false');
                /**
                 * toggle 事件监听
                 */
                this.addEventListener('toggle', function(event) {
                    var url=this.parentNode.querySelector('span').getAttribute("data-url");
                    var name=this.parentNode.querySelector('span').getAttribute("data-name");
                    var id=this.parentNode.querySelector('span').getAttribute("data-id");
                    var layerId=this.parentNode.querySelector('span').getAttribute("data-layerId");
                    var showFields=this.parentNode.querySelector('span').getAttribute("data-showFields");
                    var node={
                        url:url,
                        name:name,
                        id:id,
                        layerId:layerId,
                        showFields:showFields
                    }
                    if(event.detail.isActive){
                        that.addLayer(node);
                    }else {
                        that.removeLayer(node);
                    }

                    //  that.curLandUseFiled=this.data("usefiled");
                    //event.detail.isActive 可直接获取当前状态
                    // this.parentNode.querySelector('span').innerText = '数据资源：' + (event.detail.isActive ? 'true' : 'false');
                });
            });
        },
        initOpt:function () {
        },
        initUIEvent:function () {
            var that=this;
            //识别
            $("#J_identify").click(function () {
                if($("#J_identify").hasClass("active")){
                    $("#J_identify").attr("title","点击查询");
                    that.removeAllFeatureLayer();
                    // $('#mapdiv').css('cursor', 'default');
                    $("#J_identify").removeClass("active");
                }else {
                    $("#J_identify").addClass("active")
                    $("#J_identify").attr("title","关闭查询");
                    that.addAllQueryLayer();
                    // $('#mapdiv').css('cursor', 'help');
                }

            });
        },




        /**
         * 添加图层
         * @param node
         */
        addLayer:function (node) {
            var name=node.name;
            var url=node.url;
            if(url==null){
                return;
            }
            var layerId=node.layerId;
            if(layerId==null||layerId==undefined)
                layerId="0";
            var imgLayer=new MapImageLayer({
                id:node.id,
                title:name,
                url:url,
                sublayers: [{
                    id: layerId
                }]
            });
            Context.view.map.layers.add(imgLayer);
            var html='';
            var showFields=node.showFields;
            html+='<option data-id="'+node.id+'_fid" value="'+node.id+'_fid" data-showfields="'+showFields+'" data-url="'+url+'" data-layerid="'+layerId+'" data-name="'+name+'">'+name+'</option>';
            $("#J_selectIdentifyLayer").append(html);
            imgLayer.when(function(){
                Context.view.extent = imgLayer.fullExtent;
            });
        },
        addLayerDefault:function () {
            var url="http://112.54.43.227:92/arcgis/rest/services/bhxcghproject/MapServer";

            var imgLayer=new MapImageLayer({
                id:"11111",
                title:"滨海新城项目地图",
                url:url,
                // sublayers: [{
                //     id: layerId
                // }]
            });
            Context.view.map.layers.add(imgLayer);
            imgLayer.when(function(){
                Context.view.extent = imgLayer.fullExtent;
            });
        },
        /**
         * 批量移除图层
         * @param node
         */
        removeLayers:function (nodesArr) {
            for(var i=0;i<nodesArr.length;i++){
                var node=nodesArr[i];
                this.removeLayer(node);
            }
        },
        /**
         * 移除图层
         */
        removeLayer:function (node) {
            var layer= Context.view.map.findLayerById(node.id);
            if(layer!=null){
                Context.view.map.layers.remove(layer);
            }

            var fid=node.id+"_fid"
            $("#J_selectIdentifyLayer option[value='"+fid+"']").remove();

            var fl= Context.view.map.findLayerById(fid);
            if(fl!=null){
                Context.view.map.layers.remove(fl);
            }

        },


        /**
         * 添加所有查询图层
         */
        addAllQueryLayer:function(){
            var that=this;
            that.removeAllFeatureLayer();

            $("#J_selectIdentifyLayer  option").each(function(){
                var $SelectOpt=$(this);
                var value=$SelectOpt.val();
                if(value!=null&&value!=""&value!=undefined){
                    var showFields=$SelectOpt.data("showfields");
                    var url=$SelectOpt.data("url");
                    var layerId=$SelectOpt.data("layerid");
                    var name=$SelectOpt.data("name");
                    var id=$SelectOpt.data("id");
                    var content="";
                    if(showFields!=undefined){
                        content=" [{ \"type\": \"fields\", \"fieldInfos\": [";
                        showFields.split(",").forEach(function (value) {
                            // content+="{ \"fieldName\":\""+value.split(":")[0]+"\",\"label\": \""+value.split(":")[1]+"\",\"visible\": true},";
                            content+="{ \"fieldName\":\""+value.split(":")[0]+"\",\"label\": \""+value.split(":")[0]+"\",\"visible\": true},";
                        });
                        content= content.substring(0,content.length-1);
                        content+="]}]";
                    }
                    if(content!=""){
                        content=JSON.parse(content);
                    }
                    if(layerId==null||layerId==undefined)
                        layerId="0";
                    var temTitle="<span >"+name+"-图层详情</span>";
                    if(url==""||url==undefined)
                        return;
                    var featureLayer=new FeatureLayer({
                        id:id,
                        url:url+"/"+layerId,
                        title: name,
                        name: name,
                        visible:true,
                        opacity:0,
                        legendEnabled:false,
                        popupTemplate: {
                            title: temTitle,
                            content:content,
                            overwriteActions: true
                        }
                    });
                    Context.view.map.layers.add(featureLayer);
                }

            });
        },
        /**
         * 移除所有的识别查询数据
         */
        removeAllFeatureLayer:function(){
            var $select=$("#J_selectIdentifyLayer").get(0);
            for(var i = 0; i < $select.options.length; i++){
                var $option=$select.options[i];
                var id=$option.value;
                if(id!=""&&id!=null&&id!=undefined){
                    var fl= Context.view.map.findLayerById(id);
                    Context.view.map.layers.remove(fl);
                }
            }
        },

    });
});
